import json

import redis
import settings
from dataclasses import dataclass

from credit_voice_service.storage.session_info import SessionInfo
from credit_voice_service.utils import database_utils


class RedisTool:
    def __init__(self, host=settings.DM_REDIS_HOST, port=settings.DM_REDIS_PORT, password=settings.DM_REDIS_PASSWORD,
                 db=settings.DM_REDIS_DB):
        self.redis = redis.Redis(host=host, port=port, password=password, db=db)

    # 对话开始初始化用户数据
    def init_case_data_to_redis(self, session_id):
        # 进程开始时，从平台接口获取用户信息数据，并写入到redis中，同时设置过期时间为30分钟
        try:
            # 连接数据库，获取数据
            db_data = database_utils.get_case_info_by_session_id(session_id)
            # 解析db_data到session_info
            session_info = SessionInfo(
                session_id=session_id,
                case_id=db_data.get('case_id'),
                customer_id='',  # 用户id
                workspace_id=0,
                dialogue_id=0,
                faq_id=0,
                company_id=0,  # 填写正确的字段值
                customer_base_info={'age': db_data.get('age'), 'gender': db_data.get('gender'),
                                    'customer_area': db_data.get('customer_area'),
                                    'customer_name': db_data.get('customer_name')
                                    },
                collect_info={},  # 信收用户信息
                lastest_psychology_state='',  # 最新的心理状态
                lastest_user_target='',  # 最新的用户目标
                formulate_solution='',  # 制定方案
                lastest_process_stage='',  # 最新流程阶段
                context=[],  # 话术上下文
                extends_info={}  # 扩展字段
            )
            # 设置数据到Redis并设置过期时间
            # 将session_info写入Redis
            redis_key = f"session:{session_id}"
            redis_value = json.dumps(session_info.__dict__)
            self.redis.setex(redis_key, 1800, redis_value)

        except redis.RedisError as e:
            print(f"Redis Error: {str(e)}")

    # 获取session_info 同时转换为session_info对象
    def get_session_info_to_object(self, session_id):
        try:
            # 获取session_info
            redis_key = f"session:{session_id}"
            redis_value = self.redis.get(redis_key)
            # 将redis_value转换为session_info对象
            session_info = SessionInfo(**json.loads(redis_value))
            return session_info
        except redis.RedisError as e:
            print(f"Redis Error: {str(e)}")
            return None

    # 将session_info对象转换为json字符串,并写入到redis中
    def set_session_info_to_redis(self, session_info):
        try:
            # 将session_info写入Redis
            redis_key = f"session:{session_info.session_id}"
            redis_value = json.dumps(session_info.__dict__)
            self.redis.set(redis_key, redis_value)
        except redis.RedisError as e:
            print(f"Redis Error: {str(e)}")
            return False

    # 延迟删除session_info
    def delete_session_info_with_delay(self, session_id, delay=300):
        try:
            self.redis.setex(session_id, delay, "__delete_marker__")
            return True
        except redis.RedisError as e:
            print(f"Redis Error: {str(e)}")
            return False

    def exists(self, key):
        try:
            return self.redis.exists(key)
        except redis.RedisError as e:
            print(f"Redis Error: {str(e)}")
            return False


redis_tool = RedisTool()
